package server

import (
	"gitee.com/godY/daminghu-cli/common"
	"gitee.com/godY/daminghu-cli/db"
	"gitee.com/godY/daminghu-cli/handler"
	"github.com/astaxie/beego"
	"strings"
)

type ControllerInfo struct {
	ControllerName string
	ModelName      string
	//Package          string
	//PreUrl           string
	//FirstColumnName  string
	//SecondColumnName string
	//TableNameLow     string
	//TableNameUpper   string
	Fields []Field
	//Columns          []*core.Column
	handler.BaseInfo
}

//const ControllerTemplate = `//{{.Auth}}
//package {{.Package}}
//
//type {{.ControllerName}} scontroller {
//{{with .Fields}}
//	{{range .}}
//	{{.Name}}        {{.Type}}     {{.Comment}}
//	{{end}}
//{{end}}
//}
//`
var CreateControllerHandler handler.HandlerOneTableFunc = func(table *common.Table, columns []*common.Column) {

	beego.Debug("CreateControllerHandler")

	fileds := make([]Field, 0)
	fieldCommont := ""
	fieldName := ""
	for _, column := range columns {

		fieldCommont = "`db:\"" + column.Name + "\"` //" + handler.ConvertComment(column.Comment)
		//moduleCommont = "`json:\"" + strings.ToLower(column.Name) + "\"`"
		fieldName = strings.ToUpper(column.Name[:1]) + strings.ToLower(column.Name[1:])
		fieldType, ok := db.DBTYPE[column.SQLType.Name]
		if !ok {
			fieldType = "string"
		}

		fileds = append(fileds, Field{fieldName, fieldType, fieldCommont})
	}

	scontrollerinfo := ControllerInfo{}
	scontrollerinfo.SetUp()
	//scontrollerinfo.Auth = common.CreateAuthor()
	scontrollerinfo.ControllerName = strings.ToUpper(table.Name) + "_CONTROLLER"
	scontrollerinfo.ModelName = strings.ToUpper(table.Name) + "_MODEL"
	scontrollerinfo.Package = "api"
	scontrollerinfo.TableNameLow = strings.ToLower(table.Name)
	scontrollerinfo.TableNameUpper = strings.ToUpper(table.Name)
	scontrollerinfo.FirstColumnName = columns[0].Name
	if len(columns) > 1 {
		scontrollerinfo.SecondColumnName = columns[1].Name
	} else {
		scontrollerinfo.SecondColumnName = "y" + columns[0].Name
	}
	scontrollerinfo.Fields = fileds
	scontrollerinfo.Columns = columns

	createServerFile("api/"+"api_"+strings.ToLower(table.Name)+".go", "controller.y", scontrollerinfo)
}
